package cn.xiaolang.thread.threadlocal;

import lombok.extern.slf4j.Slf4j;
import org.junit.Assert;
import org.junit.Test;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 子线程可以继承父类的共享变量
 * </p>
 * Executor线程池下因为线程复用会有些问题，ThreadLocal参数用完记得remove
 *
 * @author fuhw/Dean
 * @date 2017年8月3日
 */
@Slf4j
public class ThreadLocalInheritable {

    private static final ThreadLocal<String> LOCAL_ONE = new InheritableThreadLocal<>();

    /**
     * 示例：用线程池测试：t1,t2,共享线程变量,t3 不共享
     * 期望：t1,t2取值相同，t3取值为null
     * 实际：t1,t2取值相同，t3取值为null 或 有值
     * 分析：Runnable只是线程方法,调用start才会使用线程执行，
     * <p>
     * 线程池把线程提交到队列,当被调用的时候如果存在空闲线程就直接复用线程,
     * 仅仅是调用了用户提交的run方法.所以当ThreadLocal参数使用完,记得调用remove方法,
     */
    @Test
    public void testByExecutors() throws InterruptedException {
        ExecutorService threadPool = Executors.newFixedThreadPool(4);
        for (int i = 0; i < 100; i++) {
            final String value = "A" + i;
            Runnable one = () -> {
                LOCAL_ONE.set(value);
                log.info("get:{}", LOCAL_ONE.get());
                Assert.assertEquals(value, LOCAL_ONE.get());
                Runnable tow = () -> Assert.assertEquals(value, LOCAL_ONE.get());
                threadPool.execute(tow);
            };
            threadPool.execute(one);
            TimeUnit.MILLISECONDS.sleep(100);
            Runnable three = () -> log.info("get:{}", LOCAL_ONE.get());
            threadPool.execute(three);
        }
    }

    /**
     * 示例：用线程池测试：t1,t2,共享线程变量,t3 不共享
     * 期望：t1,t2取值相同，t3取值为null
     * 实际：t1,t2取值相同，t3取值为null （符合预期）
     */
    @Test
    public void testByThread() throws InterruptedException {
        for (int i = 0; i < 10000; i++) {
            // t1,t2 父子级线程共享变量
            final String value = "A" + i;
            new Thread(() -> {
                LOCAL_ONE.set(value);
                Assert.assertEquals(value, LOCAL_ONE.get());
                new Thread(() -> {
                    Assert.assertEquals(value, LOCAL_ONE.get());
                }).start();
                LOCAL_ONE.remove();
            }).start();
            //t3跟t1同级别
            new Thread(() -> {
                Assert.assertNull(LOCAL_ONE.get());
            }).start();
        }
    }
}
